import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import axios from '../axios';

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'));
  const role  = ref<string | null>(localStorage.getItem('role'));

  const isAuthenticated = computed(() => !!token.value);

  // 新增角色判断变量
  const isGuest = computed(() => role.value === 'guest');
  const isUser = computed(() => role.value === 'user');
  const isCoach = computed(() => role.value === 'coach');
  const isAdmin = computed(() => role.value === 'admin');
  

const login = async (username: string, password: string ,captcha: string) => {
    try {
      const response = await axios.post('/auth/login', { username, password});
      const responsedata =response.data;
      token.value = responsedata.data.token;
      role.value =responsedata.data.role;
      console.log("user jwt token:"+token.value)
      console.log("user permission role:"+role.value)
      localStorage.setItem('token', token.value || '');
      localStorage.setItem('role', role.value || '');
    } catch (error) {
      throw error;
    }
  };

  const register = async (username: string, password: string, role: string, captcha: string) => {
    try {
      const response = await axios.post('/auth/register', {
        username,
        password,
        role: { name: role }, // 将 role 包装为对象
        captcha

      });
      token.value = response.data.token;
      localStorage.setItem('token', token.value || '');
    } catch (error) {
      throw error;
    }
  };

  const logout = () => {
    token.value = null;
    role.value =null;
    localStorage.removeItem('token');
    localStorage.removeItem('role');
  };

  return {
    token,
    role,
    isAuthenticated,
    isGuest, // 是否为 guest
    isUser,  // 是否为 user
    isCoach, // 是否为 coach
    isAdmin, // 是否为 admin
    login,
    register,
    logout
  };
});
